package com.maon.mall.security.utils;

import com.mano.commons.web.constants.WebConstants;
import com.maon.mall.security.model.SsoUser;
import com.nimbusds.jwt.JWTClaimsSet;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;

/**
 * @Author: zj
 * @Description:
 * @Date: Created in 10:10 2020/11/23
 * @Modified By:
 */
public class SsoWebLoginHelper {


    public static SsoUser loginCheck(HttpServletRequest request, HttpServletResponse response) throws IOException, ParseException {
        //Authorization: bearer ce334918-e666-455a-8ecd-8bd680415d84
        String authorization = request.getHeader("Authorization");

        if (authorization == null || !authorization.startsWith(WebConstants.JWT_TOKEN_PREFIX)) {
            throw new UnapprovedClientAuthenticationException("请求头中无Authorization信息");
        }
        // 获取token
        String jwtToken = extractHeaderToken(authorization);
        // 解析token
        SsoUser ssoUser = (SsoUser) JWTClaimsSet.parse(jwtToken).getClaim(WebConstants.JWT_ENCHANCER_USER);
        return ssoUser;
    }


    /**
     * 解码 token
     * 正常的token 或者 JWT token
     *  Authorization: bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NzE3NDM0OTQsInVzZXJfbmFtZSI6ImFkbWluIiwiYXV0aG9yaXRpZXMiOlsiUk9MRV9BRE1JTiJdLCJqdGkiOiI4Y2NhMjlhZi1lYTc3LTRmZTYtOWZlMS0zMjc0MTVkY2QyMWQiLCJjbGllbnRfaWQiOiJ1c2VyLWNsaWVudCIsInNjb3BlIjpbImFsbCJdfQ.0Ik3UwB1xjX2le5luEdtVAI_MEyu_OloRRYtPOvtvwM
     * @param authorization
     * @return
     * @throws IOException
     */
    public static String extractHeaderToken(String authorization) throws IOException {
        return authorization.substring(WebConstants.JWT_TOKEN_PREFIX.length());
    }
    /**
     * 解码Client_id  client_secret
     * Authorization 要加在请求头中，格式为 Basic 空格 base64(clientId:clientSecret)
     * Authorization: Basic dXNlci1jbGllbnQ6dXNlci1zZWNyZXQtODg4OA==
     * @param authorization
     * @param request
     * @return
     * @throws IOException
     */
    public static String[] extractHeaderClient(String authorization, HttpServletRequest request) throws IOException {
        byte[] base64Token = authorization.substring(6).getBytes("UTF-8");

        byte[] decoded;
        try {
            decoded = Base64.decode(base64Token);
        } catch (IllegalArgumentException var7) {
            throw new BadCredentialsException("Failed to decode basic authentication token");
        }
        String token = new String(decoded, "UTF-8");
        int delim = token.indexOf(":");
        if (delim == -1) {
            throw new BadCredentialsException("Invalid basic authentication token");
        } else {
            return new String[]{token.substring(0, delim), token.substring(delim + 1)};
        }
    }
}
